<template>
  <div>
    <el-tree
      ref="refTree"
      node-key="id"
      :data="permissionData"
      :props="{ label: 'name' }"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
    />
    <div>
      <el-button @click="hCancel">取消</el-button>
      <el-button @click="hSave">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleDetail, assignPerm } from '@/api/settings'
import { arrTree } from '@/utils/index'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: [] // 存储权限数据
    }
  },
  created() {
    this.loadPermissionList()
    // 获取角色具备的权限
    this.loadPermission()
  },
  methods: {
    async loadPermissionList() {
      // 发送请求, 获取权限列表
      const res = await getPermissionList()
      console.log('权限列表的数据是', res)
      this.permissionData = arrTree(res.data, '0')
    },
    async loadPermission() {
      // 发送请求, 获取权限列表
      const res = await getRoleDetail(this.curId)
      console.log('角色id', res)
      // 让树状节点选中指定元素
      this.$refs.refTree.setCheckedKeys(res.data.permIds)
    },
    async hSave() {
      // 获取选中的节点
      const permIds = this.$refs.refTree.getCheckedKeys()
      // 调用接口
      await assignPerm({ id: this.curId, permIds: permIds })
      // 提示
      this.$message.success('保存成功')
      // 通过父组件去关闭弹层
      this.$emit('success')
    },
    hCancel() {
    // 通过父组件去关闭弹层
      this.$emit('close')
    }
  }
}
</script>
